import React from 'react';
import { Tooltip, Tag } from 'antd';
import moment from 'moment';
import { Link }  from 'umi';
import { getDisplayText } from '@/utils/dataDictUtil';

import { Operates, RowsTooltip } from './components';
import {
    RESUME_STATUS,
    CANDIDATE_STATUS,
    INTERVIEW_STATUS,
    RESUME_STATUS_LIST,
    NOTICE_TYPE,
    HIRE_STATUS_ENUM,
    HIRE_STATUS
} from './dictionary';
import {
    MoreOperate,
    InterviewInviteOperate,
    InterviewEditOperate,
    InterviewNoticeOperate,
    InterviewDetailOperate,
    InterviewSummaryOperate,
    InterviewStartOperate,
    InterviewPreparationOperate,
    InterviewEditPreparationOperate,
    TransferOperate,
    RecommendOperate,
    HireCancelOperate,
    HireDetailOperate,
    HireRelaunchOperate,
    HireCommunicateOperate,
    HireNoticeOperate,
    TalentsBlackListOperate,
    InterviewCopyOperate
} from './containers';

const empty = '';

export const renderPhone = val => {
    if (!val) {
        return empty;
    }
    if (val.length !== 11) return val;
    return `${val.substr(0, 3)} ${val.substr(3, 4)} ${val.substr(7, 4)}`;
};

/**
 * 候选人列表操作
 * @param {*} record
 * @param {*} onRefresh
 */
export const renderCandidateRecordOperate = (record, onRefresh, isPrincipal, isLauncher, closeBlack) => {
    const {
        candidateStatus,
        id,
        recruitTalentMatcherId,
        contactId,
        hasBlackList,
        talentCode,
        recruitList = [],
        candidateLink
    } = record;
    const copy = <InterviewCopyOperate candidateLink={candidateLink} />;
    const defaultNoticeEmployee = new Set();
    recruitList.forEach(item => {
        defaultNoticeEmployee.add(item.launchEmployeeCode);
        defaultNoticeEmployee.add(item.principalEmployeeCode);
    });
    const moveToBlack = !closeBlack ? (
        <TalentsBlackListOperate
            key={hasBlackList ? 'remove' : 'add'}
            talentCode={talentCode}
            operateType={hasBlackList ? 'remove' : 'add'}
            onRefresh={onRefresh}
            defaultNoticeEmployee={Array.from(defaultNoticeEmployee)}
            messageType={[2, 5].includes(candidateStatus) ? 0 : 2} // 同人才库加入黑名单判断条件，候选阶段非淘汰type为2
            resumeStep={2}
        />
    ) : null;
    if (!closeBlack && hasBlackList) {
        return <Operates operates={[moveToBlack]} operateType="candidate" />;
    }
    const notice = noticeType =>
        isPrincipal && <InterviewNoticeOperate candidateId={id} noticeType={noticeType} contactId={contactId} />;
    const invite = isPrincipal && <InterviewInviteOperate candidateId={id} resumeId={recruitTalentMatcherId} />;
    const edit = isPrincipal && <InterviewEditOperate candidateId={id} contactId={contactId} />;
    const transfer = <TransferOperate resumeId={recruitTalentMatcherId} />;
    const recommend = (
        <RecommendOperate weedOutDisabled={!(isPrincipal || isLauncher)} resumeId={recruitTalentMatcherId} />
    );

    const more =
        isPrincipal || isLauncher
            ? [<MoreOperate candidateId={id} resumeId={recruitTalentMatcherId} onConfirm={onRefresh} />]
            : [transfer, recommend];
    // 1 候选 2 淘汰 3 待接受 5 已取消
    const arr = [
        [],
        [invite, moveToBlack, ...more],
        [invite, notice(NOTICE_TYPE.WEED_OUT), transfer, recommend, moveToBlack],
        [edit, notice(NOTICE_TYPE.INVITE), moveToBlack, copy, ...more],
        [],
        [invite, moveToBlack, ...more],
        [edit, notice(NOTICE_TYPE.INVITE), moveToBlack, ...more],
        [edit, moveToBlack, ...more], // 逾期状态
        [edit, moveToBlack, ...more] // 拒绝状态
    ];

    return <Operates operates={arr[candidateStatus] || []} operateType="candidate"></Operates>;
};

/**
 * 面试列表操作
 * @param {*} record
 * @param {*} onRefresh
 */
export const renderInterviewRecordOperate = (record, onRefresh, isPrincipal, employeeCode, isLauncher, closeBlack) => {
    const {
        arrangeId,
        interviewStatus,
        candidateId,
        recruitTalentMatcherId,
        contactId,
        interviewEmployees = [],
        candidateInterviewRecordFlag, // 否有面试记录  有面试记录才可以查看面试详情
        currentEmployeeInterviewRecordFlag, // 当前员工是否有面试记录
        currentEmployeeInterviewPrepareFlag, // 当前员工是否有面试准备 有面试准备后才可以开始面试
        interviewPrepareFlag, // 是否有面试准备
        interviewWay, // 面试方式
        hasBlackList,
        talentCode,
        resumeLabel,
        recruitList = [],
        candidateLink // 招聘链接
    } = record;
    const defaultNoticeEmployee = new Set();
    recruitList.forEach(item => {
        defaultNoticeEmployee.add(item.launchEmployeeCode);
        defaultNoticeEmployee.add(item.principalEmployeeCode);
    });
    const moveToBlack = !closeBlack ? (
        <TalentsBlackListOperate
            key={hasBlackList ? 'remove' : 'add'}
            talentCode={talentCode}
            operateType={hasBlackList ? 'remove' : 'add'}
            onRefresh={onRefresh}
            defaultNoticeEmployee={Array.from(defaultNoticeEmployee)}
            messageType={[1].includes(resumeLabel) ? 1 : 0} // 同人才库加入黑名单判断条件，面试阶段应聘中为1
            resumeStep={3}
        />
    ) : null;
    if (!closeBlack && hasBlackList) {
        return <Operates operates={[moveToBlack]} />;
    }
    const isInterviewer = interviewEmployees.some(item => item?.employeeCode === employeeCode);
    const notice = noticeType =>
        isPrincipal && (
            <InterviewNoticeOperate candidateId={candidateId} noticeType={noticeType} contactId={contactId} />
        );
    const invite = isPrincipal && (
        <InterviewInviteOperate candidateId={candidateId} resumeId={recruitTalentMatcherId} />
    );
    const edit = isPrincipal && <InterviewEditOperate candidateId={candidateId} contactId={contactId} />;
    const detail = !!candidateInterviewRecordFlag && <InterviewDetailOperate candidateId={candidateId} />;
    const copy = <InterviewCopyOperate candidateLink={candidateLink} />;
    const summary = (isPrincipal || isLauncher) && (
        <InterviewSummaryOperate candidateId={candidateId} arrangeId={arrangeId} />
    );
    const transfer = <TransferOperate resumeId={recruitTalentMatcherId} />;
    const recommend = (
        <RecommendOperate
            weedOutDisabled={!(isPrincipal || isLauncher)}
            resumeId={recruitTalentMatcherId}
            onConfirm={onRefresh}
        />
    );
    const renderStart = show =>
        isInterviewer && show && <InterviewStartOperate candidateId={candidateId} arrangeId={arrangeId} />;
    const preparation = currentEmployeeInterviewPrepareFlag
        ? isInterviewer && <InterviewEditPreparationOperate candidateId={candidateId} arrangeId={arrangeId} />
        : isInterviewer && <InterviewPreparationOperate candidateId={candidateId} arrangeId={arrangeId} />;

    const more =
        isPrincipal || isLauncher
            ? [<MoreOperate candidateId={candidateId} resumeId={recruitTalentMatcherId} onConfirm={onRefresh} />]
            : [transfer, recommend];
    // 1 待接受 2 待面试 3 待总结 4 已通过 5 已淘汰 6 需复试 7 已取消
    let arr = [
        [],
        [edit, notice(NOTICE_TYPE.INVITE), detail, moveToBlack, copy, ...more], // 待接受
        // eslint-disable-next-line max-len
        [
            renderStart(!!interviewPrepareFlag),
            preparation,
            notice(NOTICE_TYPE.INVITE),
            detail,
            edit,
            moveToBlack,
            copy,
            ...more
        ], // 待面试
        [renderStart(!currentEmployeeInterviewRecordFlag), summary, detail, moveToBlack, copy, ...more], // 待总结
        [detail, moveToBlack, copy], // 已通过 （理论上列表中不会有这个状态的数据）
        [invite, notice(NOTICE_TYPE.WEED_OUT), detail, transfer, recommend, moveToBlack, copy], // 已淘汰
        [invite, detail, moveToBlack, copy, ...more], // 需复试
        [invite, detail, moveToBlack, copy, ...more] // 已取消 // detail不一定
    ];

    // 如果是面试作业方式

    if (interviewWay === 5) {
        arr = [
            [],
            [edit, notice(NOTICE_TYPE.INVITE), detail, moveToBlack, copy, ...more], // 待接受
            [notice(NOTICE_TYPE.INVITE), edit, detail, moveToBlack, copy, ...more],
            [summary, detail, moveToBlack, copy, ...more],
            [detail, moveToBlack, copy],
            [invite, notice(NOTICE_TYPE.WEED_OUT), detail, transfer, recommend, moveToBlack, copy], // 已淘汰
            [invite, detail, moveToBlack, copy, ...more], // 需复试
            [invite, detail, moveToBlack, copy, ...more] // 已取消 // detail不一定
        ];
    }

    arr = [
        ...arr,
        [edit, notice(NOTICE_TYPE.INVITE), detail, moveToBlack, copy, ...more],
        [edit, detail, moveToBlack, copy, ...more], // 面试阶段--逾期
        [edit, detail, moveToBlack, copy, ...more] // 面试阶段--拒绝
    ];

    return <Operates operates={arr[interviewStatus] || []}></Operates>;
};

/**
 * 录用列表操作
 * @param {*} record
 * @param {*} onRefresh
 */
export const renderHireRecordOperate = (record, onRefresh, isPrincipal, isLauncher, closeBlack) => {
    const {
        candidateId,
        recruitTalentMatcherId,
        employId,
        employStatus,
        talentName,
        hasBlackList,
        talentCode,
        resumeLabel,
        recruitList = [],
        candidateLink
    } = record;
    const copy = <InterviewCopyOperate candidateLink={candidateLink} />;

    const defaultNoticeEmployee = new Set();
    recruitList.forEach(item => {
        defaultNoticeEmployee.add(item.launchEmployeeCode);
        defaultNoticeEmployee.add(item.principalEmployeeCode);
    });
    const moveToBlack = !closeBlack ? (
        <TalentsBlackListOperate
            key={hasBlackList ? 'remove' : 'add'}
            talentCode={talentCode}
            operateType={hasBlackList ? 'remove' : 'add'}
            onRefresh={onRefresh}
            defaultNoticeEmployee={Array.from(defaultNoticeEmployee)}
            messageType={[1].includes(resumeLabel) ? 1 : 0} // 同人才库加入黑名单判断条件，录用阶段应聘中为1
            resumeStep={4}
        />
    ) : null;
    if (!closeBlack && hasBlackList) {
        return <Operates operates={[moveToBlack]} />;
    }
    const Detail = (
        <HireDetailOperate candidateId={candidateId} employId={employId} resumeId={recruitTalentMatcherId} />
    );
    const Cancel = <HireCancelOperate employId={employId} onConfirm={onRefresh} talentName={talentName} />;
    const Relaunch = <HireRelaunchOperate candidateId={candidateId} employId={employId} />;
    const Communicate = (
        <HireCommunicateOperate candidateId={candidateId} employId={employId} employStatus={employStatus} />
    );
    const Transfer = <TransferOperate resumeId={recruitTalentMatcherId} />;
    const Recommend = (
        <RecommendOperate
            weedOutDisabled={!(isPrincipal || isLauncher)}
            resumeId={recruitTalentMatcherId}
            onConfirm={onRefresh}
        />
    );
    // 当录用状态为待接受时，即employStatus=6，则增加再次发送录用邮件功能
    const HireNotice = (
        <HireNoticeOperate candidateId={candidateId} employId={employId} noticeType={NOTICE_TYPE.OFFER} />
    );
    const props = {
        candidateId,
        resumeId: recruitTalentMatcherId,
        noticeType: NOTICE_TYPE.TERMINATE,
        onConfirm: onRefresh
    };
    const More = isPrincipal || isLauncher ? [<MoreOperate {...props} />] : [Transfer, Recommend];
    // 录用状态（1=待处理 2=沟通中/需协商 3=审批中 4=审批拒绝 5=审批撤回 6=待接收 7=已接受  9=已入职 10已淘汰）
    const arr = {
        [HIRE_STATUS_ENUM.PENDING]: [Communicate, moveToBlack, copy, ...More],
        [HIRE_STATUS_ENUM.COMMUNICATING]: [Communicate, moveToBlack, copy, ...More],
        [HIRE_STATUS_ENUM.APPROVAL]: [Detail, moveToBlack, copy, ...More],
        [HIRE_STATUS_ENUM.DENIED]: [Relaunch, moveToBlack, copy, ...More],
        [HIRE_STATUS_ENUM.WITHDRAWAL]: [Relaunch, moveToBlack, copy, ...More],
        [HIRE_STATUS_ENUM.TO_BE_ACCEPTED]: [HireNotice, Detail, moveToBlack, copy, ...More],
        [HIRE_STATUS_ENUM.TO_BE_HIRED]: [Cancel, moveToBlack, copy, ...More],
        [HIRE_STATUS_ENUM.HIRED]: [Detail],
        [HIRE_STATUS_ENUM.OUT]: [Detail, moveToBlack, copy, ...More]
    };

    return <Operates operates={arr[employStatus] || []}></Operates>;

    // console.log('===================', HIRE_STATUS_ENUM);

    // return <Operates operates={[Communicate, Detail, Relaunch, Cancel, More]}></Operates>;
};

const trimZero = (str, split = '-') =>
    str
        .split(split)
        .map(item => (item.startsWith('0') ? item.substr(1) : item))
        .join(split);

/**
 * 显示简短日期，hover显示完整日期
 * 例: 9-2  10-12
 */
export function renderShortDate(dateStr, formatStr = 'MM-DD') {
    if (!dateStr) {
        return empty;
    }
    const short = trimZero(moment(dateStr).format(formatStr));
    return (
        <Tooltip placement="top" title={dateStr}>
            <span>{short}</span>
        </Tooltip>
    );
}

/**
 * 显示面试日期，hover显示完整日期
 * 例: 9-2  10-12
 */
export function renderInterviewTimeRange(startTime, endTime) {
    if (!startTime && !endTime) {
        return empty;
    }
    const date = moment(startTime || endTime).format('M-DD ');
    const fullDate = moment(startTime || endTime).format('YYYY-MM-DD ');
    const st = moment(startTime).format('HH:mm');
    const et = moment(endTime).format('HH:mm');
    return (
        <Tooltip
            placement="top"
            title={`${fullDate}${st}
                ${st && et ? '~' : ''}
                ${et}`}
        >
            <span>
                {date}
                {st}
                {st && et ? '~' : ''}
                {et}
            </span>
        </Tooltip>
    );
}

/**
 *  渲染面试管理中的状态
 *
 */
export function renderInterviewResumeStatus(status, statusHover) {
    const item = RESUME_STATUS_LIST.find(_ => _.value === status);
    if (!item) {
        return empty;
    }
    // 根据状态对应下标值映射颜色，为空则使用默认颜色。
    return (
        <Tooltip
            placement="top"
            title={
                statusHover.indexOf('‖‖') !== -1 ? (
                    <div style={{ whiteSpace: 'pre-wrap' }}>
                        {statusHover.split('‖‖')[0]}
                        <br />
                        {statusHover.split('‖‖')[1]}
                    </div>
                ) : (
                    statusHover
                )
            }
            overlayStyle={{ fontSize: '13px' }}
        >
            <span style={{ color: item.color }}>{item.text}</span>
        </Tooltip>
    );
}

/**
 *  渲染简历列表状态
 * 状态 1：待定 2： 候选 3：淘汰
 */
export function renderResumeStatus(status, record) {
    if (!status) {
        return empty;
    }
    const val = getDisplayText(RESUME_STATUS, status);
    // 根据状态对应下标值映射颜色，为空则使用默认颜色。
    const color = [null, null, null, 'rgba(0,0,0,0.25)'][status];
    return (
        <Tooltip
            title={
                record.statusInfo.indexOf('‖‖') !== -1 ? (
                    <div style={{ whiteSpace: 'pre-wrap' }}>
                        {record.statusInfo.split('‖‖')[0]}
                        <br />
                        {record.statusInfo.split('‖‖')[1]}
                    </div>
                ) : (
                    record.statusInfo
                )
            }
        >
            {color ? <span style={{ color }}>{val}</span> : val}
        </Tooltip>
    );
}
/**
 *  渲染候选人列表状态
 * 状态  1： 候选 2：淘汰 3：待接受 5:已取消
 */
export function renderCandidateStatus(status, candidateStatusHover) {
    if (!status) {
        return empty;
    }
    const val = getDisplayText(CANDIDATE_STATUS, status);
    // 根据状态对应下标值映射颜色，为空则使用默认颜色。
    const color = [null, null, 'rgba(0,0,0,0.25)', '#5590F6', null, 'rgba(0,0,0,0.25)'][status];
    const spanStyle = color ? { color } : {};
    return (
        <Tooltip
            placement="top"
            title={
                candidateStatusHover.indexOf('‖‖') !== -1 ? (
                    <div style={{ whiteSpace: 'pre-wrap' }}>
                        {candidateStatusHover.split('‖‖')[0]}
                        <br />
                        {candidateStatusHover.split('‖‖')[1]}
                    </div>
                ) : (
                    candidateStatusHover
                )
            }
        >
            <span style={spanStyle}>{val}</span>
        </Tooltip>
    );
}

/**
 *  渲染面试列表状态
 * 状态  1： 候选 2：淘汰 3：待接受 5:已取消
 */
export function renderInterviewStatus(status, statusHover) {
    const item = INTERVIEW_STATUS.find(_ => _.value === status);
    if (!item) {
        return empty;
    }
    // 根据状态对应下标值映射颜色，为空则使用默认颜色。
    return (
        <Tooltip
            placement="top"
            title={
                statusHover.indexOf('‖‖') !== -1 ? (
                    <div style={{ whiteSpace: 'pre-wrap' }}>
                        {statusHover.split('‖‖')[0]}
                        <br />
                        {statusHover.split('‖‖')[1]}
                    </div>
                ) : (
                    statusHover
                )
            }
        >
            <span style={{ color: item.color }}>{item.text}</span>
        </Tooltip>
    );
}

/**
 *  渲染面试列表状态
 */
export function renderHireStatus(status, statusHover, talentEmployeeCode) {
    const item = HIRE_STATUS.find(_ => _.value === status);
    if (!item) {
        return empty;
    }
    let child = <span>{item.text}</span>;
    if (HIRE_STATUS_ENUM.TO_BE_HIRED === status || HIRE_STATUS_ENUM.HIRED === status) {
        child = (
            <Link
                to={{
                    pathname: '/office/personnelManagement/onboardAndLeave/entryManage/entryEmployeeDetail',
                    query: {
                        entryPersonnelCode: talentEmployeeCode
                    }
                }}
            >
                {item.text}
            </Link>
        );
    }
    // 根据状态对应下标值映射颜色，为空则使用默认颜色。
    return (
        <Tooltip
            placement="top"
            title={
                statusHover.indexOf('‖‖') !== -1 ? (
                    <div style={{ whiteSpace: 'pre-wrap' }}>
                        {statusHover.split('‖‖')[0]}
                        <br />
                        {statusHover.split('‖‖')[1]}
                    </div>
                ) : (
                    statusHover
                )
            }
        >
            {child}
        </Tooltip>
    );
}

/**
 * 渲染名字和已读标识(注：2021.06.04加入黑名单标识显示判断 By Tofu)
 * 圆点(未读) + 姓名
 * @param {*} name 姓名
 * @param {*} readFlag 是否已读
 */
export function renderNameWithReadFlag(name, readFlag, showReadFlag, hasBlackList) {
    if (!name) {
        return empty;
    }
    const nameEle = <span style={{ marginLeft: '10px', cursor: 'pointer', whiteSpace: 'nowrap' }}>{name}</span>;
    return (
        <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap' }}>
            <div
                style={{
                    width: 6,
                    height: 6,
                    borderRadius: '50%',
                    background: !readFlag && showReadFlag ? '#FFA22D' : 'transparent'
                }}
            ></div>
            {nameEle}
            {hasBlackList && (
                <Tag color="black" style={{ marginLeft: 8 }}>
                    黑名单
                </Tag>
            )}
        </div>
    );
}

/**
 * 渲染名字和已读标识
 * 与 renderNameWithReadFlag一起使用
 * @param {*} name 姓名
 * @param {*} readFlag 是否已读
 */
export function renderNameWithReadFlagTitle(title) {
    return <span style={{ marginLeft: '16px' }}>{title}</span>;
}

/**
 * 学历
 * @param {*} val
 * @param {*} talentEduDetailVOList
 */
export function renderTalentDegree(val, talentEduDetailVOList = []) {
    const format = d => trimZero(moment(d).format('YYYY-MM'));

    const arr = talentEduDetailVOList
        .map(item => {
            const { startTime, endTime, graduateSchool, major } = item;
            if (!startTime) {
                return null;
            }
            if (!graduateSchool && !major) {
                return null;
            }

            const label = `${format(startTime)}~${endTime ? format(endTime) : '至今'}`;
            const value = [graduateSchool, major].join('/');
            return { label, value };
        })
        .filter(_ => _);
    return <RowsTooltip rows={arr}>{val}</RowsTooltip>;
}
/**
 * 最近工作
 * @param {*} val
 * @param {*} talentWorkDetailVOList
 */
export function renderLastPost(val, talentWorkDetailVOList = []) {
    const format = d => trimZero(moment(d).format('YYYY-MM'));

    const arr = talentWorkDetailVOList
        .map(item => {
            const { startTime, endTime, companyName, positionName } = item;
            if (!startTime) {
                return null;
            }
            if (!companyName && !positionName) {
                return null;
            }

            const label = `${format(startTime)}~${endTime ? format(endTime) : '至今'}`;
            const value = [companyName, positionName].join('/');
            return { label, value };
        })
        .filter(_ => _);
    return <RowsTooltip rows={arr}>{val}</RowsTooltip>;
}
